const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

// 验证JWT中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: '未授权访问' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.userId;
    next();
  } catch (error) {
    return res.status(403).json({ error: '无效的令牌' });
  }
};

// 获取用户的所有习惯
router.get('/', authenticateToken, (req, res) => {
  try {
    const includeArchived = req.query.include_archived === 'true';
    const whereClause = includeArchived ? `WHERE user_id = ${req.userId}` : 
                                         `WHERE user_id = ${req.userId} AND (is_archived = 0 OR is_archived IS NULL)`;
    
    const habits = [];
    const results = global.db.exec(`SELECT * FROM habits ${whereClause}`);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        habits.push(habit);
      }
    }
    
    res.json(habits);
  } catch (error) {
    console.error('获取习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取已归档的习惯
router.get('/archived', authenticateToken, (req, res) => {
  try {
    const habits = [];
    const results = global.db.exec(`
      SELECT * FROM habits 
      WHERE user_id = ${req.userId} AND is_archived = 1
      ORDER BY id DESC
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        habits.push(habit);
      }
    }
    
    res.json(habits);
  } catch (error) {
    console.error('获取已归档习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取已完成的习惯
router.get('/completed', authenticateToken, (req, res) => {
  try {
    const habits = [];
    
    // 首先获取用户创建的所有习惯ID
    const habitsResult = global.db.exec(`
      SELECT id FROM habits 
      WHERE user_id = ${req.userId}
    `);
    
    if (habitsResult.length === 0 || habitsResult[0].values.length === 0) {
      return res.json([]);
    }
    
    const habitIds = habitsResult[0].values.map(row => row[0]);
    
    // 对每个习惯，检查完成情况
    for (const habitId of habitIds) {
      // 查询该习惯的所有信息
      const habitDetailsResult = global.db.exec(`
        SELECT * FROM habits WHERE id = ${habitId}
      `);
      
      if (habitDetailsResult.length === 0 || habitDetailsResult[0].values.length === 0) {
        continue;
      }
      
      const { columns, values } = habitDetailsResult[0];
      const habit = {};
      columns.forEach((col, i) => {
        habit[col] = values[0][i];
      });
      
      // 查询该习惯的连续完成记录
      const completionsResult = global.db.exec(`
        SELECT COUNT(*) FROM habit_completions 
        WHERE habit_id = ${habitId}
      `);
      
      let completions = 0;
      if (completionsResult.length > 0 && completionsResult[0].values.length > 0) {
        completions = completionsResult[0].values[0][0];
      }
      
      // 如果完成次数超过30次，认为习惯已经形成
      if (completions >= 30) {
        habit.completions = completions;
        habits.push(habit);
      }
    }
    
    res.json(habits);
  } catch (error) {
    console.error('获取已完成习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取习惯的动机
router.get('/:id/motivation', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查习惯是否存在且属于当前用户
    const habitStmt = global.db.prepare('SELECT * FROM habits WHERE id = ? AND user_id = ?');
    const habit = habitStmt.getAsObject([id, req.userId]);
    
    if (!habit.id) {
      return res.status(404).json({ error: '习惯不存在' });
    }
    
    res.json({ 
      id: habit.id,
      title: habit.title,
      motivation: habit.motivation || "" 
    });
  } catch (error) {
    console.error('获取习惯动机错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新习惯的动机
router.put('/:id/motivation', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    const { motivation } = req.body;
    
    if (motivation === undefined) {
      return res.status(400).json({ error: '动机内容不能为空' });
    }
    
    // 检查习惯是否存在且属于当前用户
    const habitStmt = global.db.prepare('SELECT * FROM habits WHERE id = ? AND user_id = ?');
    const habit = habitStmt.getAsObject([id, req.userId]);
    
    if (!habit.id) {
      return res.status(404).json({ error: '习惯不存在' });
    }
    
    // 更新动机
    const updateStmt = global.db.prepare('UPDATE habits SET motivation = ? WHERE id = ?');
    updateStmt.run([motivation, id]);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ message: '习惯动机已更新' });
  } catch (error) {
    console.error('更新习惯动机错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取习惯完成记录
router.get('/:id/completions', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查习惯是否存在且属于当前用户
    const habitStmt = global.db.prepare('SELECT * FROM habits WHERE id = ? AND user_id = ?');
    const habit = habitStmt.getAsObject([id, req.userId]);
    
    if (!habit.id) {
      return res.status(404).json({ error: '习惯不存在' });
    }
    
    // 获取完成记录
    const completions = [];
    const results = global.db.exec(`
      SELECT * FROM habit_completions 
      WHERE habit_id = ${id}
      ORDER BY completed_at DESC
      LIMIT 50
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const completion = {};
        columns.forEach((col, i) => {
          completion[col] = row[i];
        });
        completions.push(completion);
      }
    }
    
    // 计算统计数据
    const stats = {
      total: completions.length,
      streak: 0,
      last_completed: completions.length > 0 ? completions[0].completed_at : null
    };
    
    res.json({
      habit,
      completions,
      stats
    });
  } catch (error) {
    console.error('获取完成记录错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取推荐习惯
router.get('/recommendations', authenticateToken, (req, res) => {
  try {
    // 检查popular_habits表是否存在
    const tableExistsResult = global.db.exec(`
      SELECT name FROM sqlite_master 
      WHERE type='table' AND name='popular_habits'
    `);
    
    // 如果表不存在，返回空数组
    if (tableExistsResult.length === 0 || tableExistsResult[0].values.length === 0) {
      return res.json([]);
    }
    
    // 获取用户已有的习惯标题
    const userHabitsResult = global.db.exec(`
      SELECT title FROM habits WHERE user_id = ${req.userId}
    `);
    
    let userHabitTitles = [];
    if (userHabitsResult.length > 0) {
      userHabitTitles = userHabitsResult[0].values.map(row => row[0].toLowerCase());
    }
    
    const recommendations = [];
    
    // 获取推荐习惯
    const results = global.db.exec(`
      SELECT * FROM popular_habits
      ORDER BY popularity DESC
      LIMIT 10
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        
        // 过滤掉用户已有的习惯
        if (!userHabitTitles.includes(habit.title.toLowerCase())) {
          recommendations.push(habit);
        }
      }
    }
    
    res.json(recommendations);
  } catch (error) {
    console.error('获取推荐习惯错误:', error);
    res.json([]); // 出错时返回空数组
  }
});

// 获取用户统计数据
router.get('/stats', authenticateToken, (req, res) => {
  try {
    // 获取用户动机分数
    const userResult = global.db.exec(`SELECT motivation_score FROM users WHERE id = ${req.userId}`);
    let motivationScore = 0;
    if (userResult.length > 0 && userResult[0].values.length > 0) {
      motivationScore = userResult[0].values[0][0];
    }
    
    // 获取习惯总数
    const habitsResult = global.db.exec(`SELECT COUNT(*) FROM habits WHERE user_id = ${req.userId}`);
    let totalHabits = 0;
    if (habitsResult.length > 0 && habitsResult[0].values.length > 0) {
      totalHabits = habitsResult[0].values[0][0];
    }
    
    // 获取本月完成数
    const currentDate = new Date();
    const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).toISOString();
    const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).toISOString();
    
    const monthlyResult = global.db.exec(`
      SELECT COUNT(*) FROM habit_completions c
      JOIN habits h ON c.habit_id = h.id
      WHERE h.user_id = ${req.userId}
      AND c.completed_at BETWEEN '${firstDayOfMonth}' AND '${lastDayOfMonth}'
    `);
    
    let monthlyCompletions = 0;
    if (monthlyResult.length > 0 && monthlyResult[0].values.length > 0) {
      monthlyCompletions = monthlyResult[0].values[0][0];
    }
    
    // 计算连续天数
    let streakCount = 0;
    
    // 获取用户完成习惯的日期列表（按日期分组）
    const streakResult = global.db.exec(`
      SELECT date(c.completed_at) as completion_date, COUNT(*) as count
      FROM habit_completions c
      JOIN habits h ON c.habit_id = h.id
      WHERE h.user_id = ${req.userId}
      GROUP BY date(c.completed_at)
      ORDER BY date(c.completed_at) DESC
    `);
    
    if (streakResult.length > 0 && streakResult[0].values.length > 0) {
      const { values } = streakResult[0];
      
      // 检查今天是否有完成
      const today = new Date().toISOString().split('T')[0];
      let currentDate = values[0][0].split('T')[0]; // 最新一天的日期
      
      // 如果今天没有完成习惯，连续天数为0
      if (currentDate !== today) {
        streakCount = 0;
      } else {
        streakCount = 1; // 至少包含今天
        
        // 从第二条记录开始检查
        for (let i = 1; i < values.length; i++) {
          const prevDate = new Date(currentDate);
          prevDate.setDate(prevDate.getDate() - 1);
          const expectedPrevDate = prevDate.toISOString().split('T')[0];
          
          const actualPrevDate = values[i][0].split('T')[0];
          
          if (expectedPrevDate === actualPrevDate) {
            streakCount++;
            currentDate = actualPrevDate;
          } else {
            break; // 连续性中断
          }
        }
      }
    }
    
    // 获取成就徽章
    const badges = calculateBadges(streakCount, monthlyCompletions, totalHabits, motivationScore);
    
    res.json({
      streak_count: streakCount,
      monthly_completions: monthlyCompletions,
      total_habits: totalHabits,
      motivation_score: motivationScore,
      badges: badges
    });
  } catch (error) {
    console.error('获取统计数据错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取习惯详细统计数据
router.get('/:id/stats/detail', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查习惯是否存在且属于当前用户
    const habitStmt = global.db.prepare('SELECT * FROM habits WHERE id = ? AND user_id = ?');
    const habit = habitStmt.getAsObject([id, req.userId]);
    
    if (!habit.id) {
      return res.status(404).json({ error: '习惯不存在' });
    }
    
    // 获取完成记录和统计数据
    // 1. 总完成次数
    const totalCompletionsResult = global.db.exec(`
      SELECT COUNT(*) FROM habit_completions WHERE habit_id = ${id}
    `);
    
    let totalCompletions = 0;
    if (totalCompletionsResult.length > 0 && totalCompletionsResult[0].values.length > 0) {
      totalCompletions = totalCompletionsResult[0].values[0][0];
    }
    
    // 2. 当前连续完成天数
    const streakResult = global.db.exec(`
      WITH dates AS (
        SELECT completed_at, 
               JULIANDAY(completed_at) - JULIANDAY(MIN(completed_at) OVER ()) - 
               ROW_NUMBER() OVER (ORDER BY completed_at) AS grp
        FROM habit_completions
        WHERE habit_id = ${id}
        ORDER BY completed_at DESC
      )
      SELECT COUNT(*) 
      FROM dates 
      WHERE grp = (SELECT grp FROM dates LIMIT 1)
    `);
    
    let currentStreak = 0;
    if (streakResult.length > 0 && streakResult[0].values.length > 0) {
      currentStreak = streakResult[0].values[0][0];
    }
    
    // 3. 最长连续完成天数
    const longestStreakResult = global.db.exec(`
      WITH dates AS (
        SELECT completed_at, 
               JULIANDAY(completed_at) - JULIANDAY(MIN(completed_at) OVER ()) - 
               ROW_NUMBER() OVER (ORDER BY completed_at) AS grp
        FROM habit_completions
        WHERE habit_id = ${id}
      ),
      streaks AS (
        SELECT grp, COUNT(*) as streak_length
        FROM dates
        GROUP BY grp
      )
      SELECT MAX(streak_length) FROM streaks
    `);
    
    let longestStreak = 0;
    if (longestStreakResult.length > 0 && longestStreakResult[0].values.length > 0) {
      longestStreak = longestStreakResult[0].values[0][0];
    }
    
    // 4. 完成率（过去30天）
    const last30DaysResult = global.db.exec(`
      SELECT COUNT(*) FROM habit_completions
      WHERE habit_id = ${id}
      AND completed_at >= date('now', '-30 days')
    `);
    
    let completionsLast30Days = 0;
    if (last30DaysResult.length > 0 && last30DaysResult[0].values.length > 0) {
      completionsLast30Days = last30DaysResult[0].values[0][0];
    }
    
    const completionRate = Math.round((completionsLast30Days / 30) * 100);
    
    // 5. 每月完成情况
    const monthlyCompletionsResult = global.db.exec(`
      SELECT strftime('%Y-%m', completed_at) as month, COUNT(*) as count
      FROM habit_completions
      WHERE habit_id = ${id}
      GROUP BY month
      ORDER BY month
    `);
    
    const monthlyCompletions = {};
    if (monthlyCompletionsResult.length > 0) {
      const { values } = monthlyCompletionsResult[0];
      for (const row of values) {
        monthlyCompletions[row[0]] = row[1];
      }
    }
    
    // 6. 最近一次完成时间
    const lastCompletionResult = global.db.exec(`
      SELECT completed_at FROM habit_completions
      WHERE habit_id = ${id}
      ORDER BY completed_at DESC
      LIMIT 1
    `);
    
    let lastCompletion = null;
    if (lastCompletionResult.length > 0 && lastCompletionResult[0].values.length > 0) {
      lastCompletion = lastCompletionResult[0].values[0][0];
    }
    
    // 整合所有统计数据
    const stats = {
      habit_id: parseInt(id),
      habit_title: habit.title,
      total_completions: totalCompletions,
      current_streak: currentStreak,
      longest_streak: longestStreak,
      completion_rate: completionRate,
      monthly_completions: monthlyCompletions,
      last_completion: lastCompletion,
      created_at: habit.created_at,
      difficulty: habit.difficulty
    };
    
    res.json(stats);
  } catch (error) {
    console.error('获取习惯详细统计数据错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 计算成就徽章
function calculateBadges(streakCount, monthlyCompletions, totalHabits, motivationScore) {
  const badges = [];
  
  // 连续天数徽章
  if (streakCount >= 3) {
    badges.push({
      id: 'streak_3',
      name: '3天连胜',
      icon: 'medal',
      color: 'yellow'
    });
  }
  if (streakCount >= 7) {
    badges.push({
      id: 'streak_7',
      name: '7天连胜',
      icon: 'medal',
      color: 'yellow'
    });
  }
  if (streakCount >= 30) {
    badges.push({
      id: 'streak_30',
      name: '30天连胜',
      icon: 'medal',
      color: 'yellow'
    });
  }
  
  // 完成次数徽章
  if (monthlyCompletions >= 10) {
    badges.push({
      id: 'completions_10',
      name: '坚持不懈',
      icon: 'leaf',
      color: 'blue'
    });
  }
  if (monthlyCompletions >= 30) {
    badges.push({
      id: 'completions_30',
      name: '习惯大师',
      icon: 'leaf',
      color: 'blue'
    });
  }
  
  // 习惯数量徽章
  if (totalHabits >= 3) {
    badges.push({
      id: 'habits_3',
      name: '习惯启动',
      icon: 'fire',
      color: 'green'
    });
  }
  
  // 动机分数徽章
  if (motivationScore >= 50) {
    badges.push({
      id: 'motivation_50',
      name: '动力充沛',
      icon: 'bolt',
      color: 'purple'
    });
  }
  
  return badges;
}

// 获取进度图表数据
router.get('/chart', authenticateToken, (req, res) => {
  try {
    // 获取最近6个月的数据
    const labels = [];
    const completionData = [];
    const motivationData = [];
    
    const currentDate = new Date();
    
    // 生成最近6个月的标签
    for (let i = 5; i >= 0; i--) {
      const month = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1);
      const monthName = month.toLocaleString('zh-CN', { month: 'short' });
      labels.push(monthName);
      
      // 计算每月的完成率
      const firstDay = new Date(month.getFullYear(), month.getMonth(), 1).toISOString();
      const lastDay = new Date(month.getFullYear(), month.getMonth() + 1, 0).toISOString();
      
      // 获取该月的习惯完成次数
      const completionsResult = global.db.exec(`
        SELECT COUNT(*) FROM habit_completions c
        JOIN habits h ON c.habit_id = h.id
        WHERE h.user_id = ${req.userId}
        AND c.completed_at BETWEEN '${firstDay}' AND '${lastDay}'
      `);
      
      let completionsCount = 0;
      if (completionsResult.length > 0 && completionsResult[0].values.length > 0) {
        completionsCount = completionsResult[0].values[0][0];
      }
      
      // 获取该月的习惯总数（注意：这里没有使用created_at字段）
      const habitsResult = global.db.exec(`
        SELECT COUNT(*) FROM habits 
        WHERE user_id = ${req.userId}
      `);
      
      let habitsCount = 0;
      if (habitsResult.length > 0 && habitsResult[0].values.length > 0) {
        habitsCount = habitsResult[0].values[0][0];
      }
      
      // 计算完成率 (如果没有习惯，则为0%)
      const daysInMonth = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
      const completionRate = habitsCount > 0 ? (completionsCount / (habitsCount * daysInMonth)) * 100 : 0;
      completionData.push(Math.min(Math.round(completionRate), 100));
      
      // 获取用户的实际动机分数，而不是估算的分数
      const userResult = global.db.exec(`SELECT motivation_score FROM users WHERE id = ${req.userId}`);
      let userMotivationScore = 50; // 默认值
      
      if (userResult.length > 0 && userResult[0].values.length > 0) {
        userMotivationScore = userResult[0].values[0][0];
      }
      
      // 如果是当前月，使用用户的实际动机分数
      if (i === 0) {
        motivationData.push(userMotivationScore);
      } else {
        // 对于历史月份，仍然使用估算的分数
        const motivationScore = Math.min(Math.round(50 + completionRate / 2), 100);
        motivationData.push(motivationScore);
      }
    }
    
    res.json({
      labels,
      completion_data: completionData,
      motivation_data: motivationData
    });
  } catch (error) {
    console.error('获取图表数据错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 创建新习惯
router.post('/', authenticateToken, (req, res) => {
  try {
    const { title, difficulty, trigger_type, trigger_data } = req.body;
    
    // 插入新习惯
    const stmt = global.db.prepare(
      'INSERT INTO habits (user_id, title, difficulty, trigger_type, trigger_data) VALUES (?, ?, ?, ?, ?)'
    );
    stmt.run([req.userId, title, difficulty, trigger_type, trigger_data || '']);
    
    // 获取最后插入的ID
    const idResult = global.db.exec('SELECT last_insert_rowid() as id')[0];
    const habitId = idResult.values[0][0];
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ 
      id: habitId,
      title,
      difficulty,
      trigger_type,
      trigger_data: trigger_data || '',
      created_at: new Date().toISOString()
    });
  } catch (error) {
    console.error('创建习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 完成习惯
router.post('/:id/complete', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    const { is_completed = false } = req.body; // 是否彻底完成
    
    // 检查习惯是否存在且属于当前用户
    const stmt = global.db.prepare('SELECT * FROM habits WHERE id = ? AND user_id = ?');
    const habit = stmt.getAsObject([id, req.userId]);
    
    if (!habit.id) {
      return res.status(404).json({ error: '习惯不存在' });
    }

    // 记录完成
    const completeStmt = global.db.prepare(
      'INSERT INTO habit_completions (habit_id, completed_at, is_completed) VALUES (?, ?, ?)'
    );
    completeStmt.run([id, new Date().toISOString(), is_completed ? 1 : 0]);

    // 如果是彻底完成，则标记习惯为归档
    if (is_completed) {
      const archiveStmt = global.db.prepare('UPDATE habits SET is_archived = 1 WHERE id = ?');
      archiveStmt.run([id]);
    }

    // 更新动机分数
    const updateStmt = global.db.prepare(
      'UPDATE users SET motivation_score = motivation_score + ? WHERE id = ?'
    );
    updateStmt.run([is_completed ? habit.difficulty * 2 : habit.difficulty, req.userId]);
    
    // 保存数据库
    global.saveDatabase();

    res.json({ 
      success: true,
      motivation_score: is_completed ? habit.difficulty * 2 : habit.difficulty,
      is_completed: is_completed
    });
  } catch (error) {
    console.error('完成习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 删除习惯
router.delete('/:id', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查习惯是否存在且属于当前用户
    const stmt = global.db.prepare('SELECT * FROM habits WHERE id = ? AND user_id = ?');
    const habit = stmt.getAsObject([id, req.userId]);
    
    if (!habit.id) {
      return res.status(404).json({ error: '习惯不存在' });
    }

    // 删除习惯及其完成记录
    const deleteCompletionsStmt = global.db.prepare('DELETE FROM habit_completions WHERE habit_id = ?');
    deleteCompletionsStmt.run([id]);
    
    const deleteHabitStmt = global.db.prepare('DELETE FROM habits WHERE id = ?');
    deleteHabitStmt.run([id]);
    
    // 保存数据库
    global.saveDatabase();

    res.json({ success: true });
  } catch (error) {
    console.error('删除习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 应用习惯推荐模板
router.post('/apply-recommendation/:id', authenticateToken, (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取推荐习惯
    const recommendationResult = global.db.exec(`SELECT * FROM popular_habits WHERE id = ${id}`);
    if (recommendationResult.length === 0 || recommendationResult[0].values.length === 0) {
      return res.status(404).json({ error: '推荐习惯不存在' });
    }
    
    const recommendation = {};
    recommendationResult[0].columns.forEach((col, i) => {
      recommendation[col] = recommendationResult[0].values[0][i];
    });
    
    // 创建习惯
    const triggerData = `每天|icon:${recommendation.icon}|color:${recommendation.color}`;
    const stmt = global.db.prepare(
      'INSERT INTO habits (user_id, title, difficulty, trigger_type, trigger_data) VALUES (?, ?, ?, ?, ?)'
    );
    stmt.run([req.userId, recommendation.title, recommendation.difficulty, 'time', triggerData]);
    
    // 获取最后插入的ID
    const idResult = global.db.exec('SELECT last_insert_rowid() as id')[0];
    const habitId = idResult.values[0][0];
    
    // 更新推荐习惯的流行度
    global.db.prepare('UPDATE popular_habits SET popularity = popularity + 1 WHERE id = ?').run([id]);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ 
      id: habitId,
      title: recommendation.title,
      difficulty: recommendation.difficulty,
      trigger_type: 'time',
      trigger_data: triggerData,
      created_at: new Date().toISOString()
    });
  } catch (error) {
    console.error('应用推荐习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取用户进度与习惯分页列表
router.get('/page/:page', authenticateToken, (req, res) => {
  try {
    const page = parseInt(req.params.page) || 1;
    const pageSize = 6; // 修改为每页显示6条
    const offset = (page - 1) * pageSize;
    const includeArchived = req.query.include_archived === 'true';
    const whereClause = includeArchived ? `WHERE user_id = ${req.userId}` : 
                                         `WHERE user_id = ${req.userId} AND (is_archived = 0 OR is_archived IS NULL)`;
    
    // 获取习惯总数
    const countResult = global.db.exec(`
      SELECT COUNT(*) FROM habits ${whereClause}
    `);
    
    let totalCount = 0;
    if (countResult.length > 0 && countResult[0].values.length > 0) {
      totalCount = countResult[0].values[0][0];
    }
    
    // 获取分页习惯
    const habits = [];
    const results = global.db.exec(`
      SELECT * FROM habits 
      ${whereClause}
      ORDER BY id DESC
      LIMIT ${pageSize} OFFSET ${offset}
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        habits.push(habit);
      }
    }
    
    res.json({
      habits,
      pagination: {
        total: totalCount,
        page: page,
        pageSize: pageSize,
        totalPages: Math.ceil(totalCount / pageSize)
      }
    });
  } catch (error) {
    console.error('获取习惯分页错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取用户信息
router.get('/user-info', authenticateToken, (req, res) => {
  try {
    const userResult = global.db.exec(`
      SELECT id, email, motivation_score, created_at FROM users 
      WHERE id = ${req.userId}
    `);
    
    if (userResult.length === 0 || userResult[0].values.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    
    const { columns, values } = userResult[0];
    const userData = {};
    
    columns.forEach((col, i) => {
      userData[col] = values[0][i];
    });
    
    // 获取完成统计
    const completionStatsResult = global.db.exec(`
      SELECT COUNT(*) as total_completions, 
      COUNT(DISTINCT date(completed_at)) as total_days,
      MAX(completed_at) as last_completion
      FROM habit_completions c
      JOIN habits h ON c.habit_id = h.id
      WHERE h.user_id = ${req.userId}
    `);
    
    if (completionStatsResult.length > 0 && completionStatsResult[0].values.length > 0) {
      userData.total_completions = completionStatsResult[0].values[0][0];
      userData.total_active_days = completionStatsResult[0].values[0][1];
      userData.last_completion = completionStatsResult[0].values[0][2];
    } else {
      userData.total_completions = 0;
      userData.total_active_days = 0;
      userData.last_completion = null;
    }
    
    // 获取习惯相关统计
    const habitsStatsResult = global.db.exec(`
      SELECT COUNT(*) as total, 
      SUM(CASE WHEN date(created_at) >= date('now', '-30 days') THEN 1 ELSE 0 END) as recent
      FROM habits 
      WHERE user_id = ${req.userId}
    `);
    
    if (habitsStatsResult.length > 0 && habitsStatsResult[0].values.length > 0) {
      userData.total_habits = habitsStatsResult[0].values[0][0];
      userData.recent_habits = habitsStatsResult[0].values[0][1];
    } else {
      userData.total_habits = 0;
      userData.recent_habits = 0;
    }
    
    // 获取已完成过的习惯数量（至少有一条完成记录的习惯）
    const completedHabitsResult = global.db.exec(`
      SELECT COUNT(DISTINCT h.id) as completed_habits
      FROM habits h
      JOIN habit_completions c ON h.id = c.habit_id
      WHERE h.user_id = ${req.userId}
    `);
    
    if (completedHabitsResult.length > 0 && completedHabitsResult[0].values.length > 0) {
      userData.completed_habits = completedHabitsResult[0].values[0][0];
    } else {
      userData.completed_habits = 0;
    }
    
    // 获取已彻底完成（归档）的习惯数量
    const archivedHabitsResult = global.db.exec(`
      SELECT COUNT(*) as archived_habits
      FROM habits 
      WHERE user_id = ${req.userId} AND is_archived = 1
    `);
    
    if (archivedHabitsResult.length > 0 && archivedHabitsResult[0].values.length > 0) {
      userData.archived_habits = archivedHabitsResult[0].values[0][0];
    } else {
      userData.archived_habits = 0;
    }
    
    res.json(userData);
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 修改密码
router.post('/change-password', authenticateToken, async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    
    if (!currentPassword || !newPassword) {
      return res.status(400).json({ error: '当前密码和新密码都是必填的' });
    }
    
    if (newPassword.length < 6) {
      return res.status(400).json({ error: '新密码长度至少为6位' });
    }
    
    // 获取用户当前密码哈希
    const userResult = global.db.exec(`
      SELECT password_hash FROM users WHERE id = ${req.userId}
    `);
    
    if (userResult.length === 0 || userResult[0].values.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    
    const storedPasswordHash = userResult[0].values[0][0];
    
    // 验证当前密码
    const bcrypt = require('bcryptjs');
    const isMatch = await bcrypt.compare(currentPassword, storedPasswordHash);
    
    if (!isMatch) {
      return res.status(400).json({ error: '当前密码不正确' });
    }
    
    // 生成新密码哈希
    const salt = await bcrypt.genSalt(10);
    const newPasswordHash = await bcrypt.hash(newPassword, salt);
    
    // 更新密码
    const updateStmt = global.db.prepare('UPDATE users SET password_hash = ? WHERE id = ?');
    updateStmt.run([newPasswordHash, req.userId]);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ message: '密码修改成功' });
  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 检查习惯标题是否存在
router.post('/check-title', authenticateToken, (req, res) => {
  try {
    const { title } = req.body;
    
    if (!title) {
      return res.status(400).json({ error: '习惯标题是必填项' });
    }
    
    // 检查该用户是否已有同名习惯
    const results = global.db.exec(`
      SELECT COUNT(*) AS count FROM habits 
      WHERE user_id = ${req.userId} AND LOWER(title) = LOWER('${title.replace(/'/g, "''")}')
    `);
    
    const exists = results.length > 0 && results[0].values[0][0] > 0;
    
    res.json({ exists });
  } catch (error) {
    console.error('检查习惯标题错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取已彻底完成的习惯（分页版本）
router.get('/mastered', authenticateToken, (req, res) => {
  try {
    const page = req.query.page ? parseInt(req.query.page) : 1;
    const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 5;
    const offset = (page - 1) * pageSize;
    
    // 查询已归档的习惯（彻底完成的习惯）
    const habits = [];
    const results = global.db.exec(`
      SELECT h.*, MAX(hc.completed_at) as last_completed_at 
      FROM habits h
      LEFT JOIN habit_completions hc ON h.id = hc.habit_id AND hc.is_completed = 1
      WHERE h.user_id = ${req.userId} AND h.is_archived = 1
      GROUP BY h.id
      ORDER BY last_completed_at DESC
      LIMIT ${pageSize} OFFSET ${offset}
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        habits.push(habit);
      }
    }
    
    // 查询总数
    const countResult = global.db.exec(`
      SELECT COUNT(*) as total 
      FROM habits 
      WHERE user_id = ${req.userId} AND is_archived = 1
    `);
    
    const total = countResult.length > 0 ? countResult[0].values[0][0] : 0;
    
    res.json({
      habits,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      }
    });
  } catch (error) {
    console.error('获取已彻底完成习惯错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

module.exports = router; 